package com.xizi.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

// 全局统一返回结果类 使用泛型T
@Data
@ApiModel(value = "全局统一返回结果")
public class Result<T> {

    //返回的状态码
    @ApiModelProperty(value = "返回码")
    private Integer code;

    //返回的消息
    @ApiModelProperty(value = "返回消息")
    private String message;

    //返回的数据 使用泛型
    @ApiModelProperty(value = "返回数据")
    private T data;

    public Result(){}

    //封装数据data
    protected static <T> Result<T> build(T data) {
        Result<T> result = new Result<T>();
        if (data != null)
            result.setData(data);
        return result;
    }


    //封装状态码code+数据data
    public static <T> Result<T> build(T body, ResultCodeEnum resultCodeEnum) {
        Result<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }
    //封装状态码code+消息message
    public static <T> Result<T> build(Integer code, String message) {
        Result<T> result = build(null);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    //执行成功 传入null 返回200状态码
    public static <T> Result<T> ok(){
        return Result.ok(null);
    }

    // 操作200成功 传入数据data
    public static<T> Result<T> ok(T data){
        Result<T> result = build(data);
        return build(data, ResultCodeEnum.SUCCESS);
    }

    public static<T> Result<T> fail(){
        return Result.fail(null);
    }

    // 操作201失败 传入数据data
    public static<T> Result<T> fail(T data){
        Result<T> result = build(data);
        return build(data, ResultCodeEnum.FAIL);
    }

    //设置返回的消息
    public Result<T> message(String msg){
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code){
        this.setCode(code);
        return this;
    }

    //判断是否是成功200
     public boolean isOk() {
        if(this.getCode().intValue() == ResultCodeEnum.SUCCESS.getCode().intValue()) {
            return true;
        }
        return false;
    }
}
